package guoanmaker.operator.business.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import guoanmaker.operator.business.model.OperatorActivityEnlist;
import guoanmaker.operator.business.model.OperatorActivityPrice;
import guoanmaker.operator.business.model.OperatorEventDetails;
import guoanmaker.operator.business.model.PayInfo;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.model.PersonalUserCoupon;
import guoanmaker.operator.business.modelnobind.OpersonalUUC;
import guoanmaker.operator.business.modelnobind.operatorEnlistDetails;
import guoanmaker.operator.business.repository.KeyValueRepository;
import guoanmaker.operator.business.repository.OperatorActivityEnlistRepository;
import guoanmaker.operator.business.repository.OperatorActivityPriceRepository;
import guoanmaker.operator.business.repository.OperatorCouponsRepository;
import guoanmaker.operator.business.repository.OperatorEventDetailsRepository;
import guoanmaker.operator.business.repository.PersonalUserCouponRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.helper.common.AjaxJson;
import guoanmaker.operator.helper.common.util.PayAnaiyInfor;
import guoanmaker.operator.helper.common.util.sendCode;

/**
 * @author wanghongwei 
 * @ClassName: OperatorActivityEnlistService 
 * @Description: OperatorActivityEnlistService
 * @date 2017/8/11
 */
@Service
public class OperatorActivityEnlistService implements OperatorActivityEnlistServiceInterface {
	private final OperatorActivityEnlistRepository operatorActivityEnlistRepository;
	private final OperatorEventDetailsRepository operatorEventDetailsRepository;
	private final PersonalUserCouponRepository personalUserCouponRepository;
	private final OperatorCouponsRepository operatorCouponsRepository;
	@PersistenceContext
	private EntityManager manager;
	@Autowired
	private PersonalUserRepository personalUserRepository;
	@Autowired
	private OperatorActivityPriceRepository activityPriceRepository;
	@Autowired
	private KeyValueRepository keyValueRepository;

	public OperatorActivityEnlistService(OperatorActivityEnlistRepository operatorActivityEnlistRepository,
			OperatorEventDetailsRepository operatorEventDetailsRepository,
			PersonalUserCouponRepository personalUserCouponRepository,
			OperatorCouponsRepository operatorCouponsRepository) {
		this.operatorActivityEnlistRepository = operatorActivityEnlistRepository;
		this.operatorEventDetailsRepository = operatorEventDetailsRepository;
		this.personalUserCouponRepository = personalUserCouponRepository;
		this.operatorCouponsRepository = operatorCouponsRepository;
	}

	/**
	 * 是否 收费 isMoney 1 收费 0 不收费 判断 活动订单 不许修改 订单 SignupStartTime 活动报名 开始时间
	 * SignupEndTime 活动报名 结束时间 判断 活动 开始、结束 时间节点 ，正在 报名 区间内 允许 报名添加订单
	 * 
	 * Enrollment 活动 最大报名票数 eventJoinPersonNum 当前参加 报名票数 报名活动 Enrollment ==0 代表 无限制
	 * 票张数
	 * 
	 * OperatorActivityPrice 类 payNum 购买订单次数限制 0 无限制 StockNum 库存 0 无限制
	 */
	@Transactional
	@Override
	public AjaxJson saveActivityEnlist(OperatorActivityEnlist activityEnlist) {
		AjaxJson ajaxJson = new AjaxJson();
		if(activityEnlist.getChannel().equals("")!=true && activityEnlist.getChannel().equals("true")==true) {
			activityEnlist.setStreamNum(String.valueOf(new Date().getTime() + (int) ((Math.random() * 9 + 1) * 100000)));// 随机生成
	        activityEnlist.setState(1);// 报名成功 1
	        activityEnlist.setBuildTime(new Date());
	        OperatorActivityEnlist operatoractivityEnlist = operatorActivityEnlistRepository.save(activityEnlist);
	        operatorEventDetailsRepository.updateEnrollmentAdd(activityEnlist.getActivityId());
	        return ajaxJson.setSuccess(true).setStatus(200).setData(operatoractivityEnlist).setMsg("报名成功 ");
		}else {
		Date date = new Date();
		if (activityEnlist.getId() != null) {
			return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("不允许修改");
		}
		if(activityEnlist.getUserId() == null ) {
			return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("用户无效");
		}
		if (activityEnlist.getUserId() != null  ) {
			PersonalUser user = personalUserRepository.findOne(activityEnlist.getUserId());
			if (user == null) {
				return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("用户无效");
			}
		}
		OperatorEventDetails eventDetails = operatorEventDetailsRepository.findOne(activityEnlist.getActivityId());
		Long startTime = eventDetails.getSignupStartTime().getTime();
		Long endTime = eventDetails.getSignupEndTime().getTime();
		Long nowTime = date.getTime();
		if (startTime > nowTime) {
			return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("报名未开始");
		} else if (endTime < nowTime) {
			return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("报名已结束");
		} else if (startTime <= nowTime && endTime > nowTime) {
			// 查询 当前 用户 在活动下 的订单 包括已经支付 和 待支付的订单 数量
			int enlistNumber = operatorActivityEnlistRepository
					.queryCountByUserIdAndActivity(activityEnlist.getUserId(), activityEnlist.getActivityId());
			// 收费
			if (eventDetails.getIsMoney() != null && eventDetails.getIsMoney() == 1) {
				// 查询 活动订单金额表
				OperatorActivityPrice activityPrice = activityPriceRepository
						.findOne(activityEnlist.getActivityPriceId());
				int priceNumber = operatorActivityEnlistRepository
						.queryCountByUserIdAndPriceId(activityEnlist.getUserId(), activityEnlist.getActivityPriceId());
				// 查询 购买数量 限制
				if (activityEnlist.getBuyNum() < activityPrice.getMinNum()) {
					return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("购买数量小于最小购买限制");
				}
				if (activityEnlist.getBuyNum() > activityPrice.getMaxNum()) {
					return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("购买数量超过最大购买限制");
				}
				// 购买数量 是否超过 库存数量
				if (activityPrice.getStockNum() != 0
						&& activityEnlist.getBuyNum() + activityPrice.getSellNum() > activityPrice.getStockNum()) {
					Integer num = activityPrice.getStockNum() - activityPrice.getSellNum();
					if (num < 0) {
						num = 0;
					}
					return ajaxJson.setSuccess(true).setStatus(200).setData(null)
							.setMsg("购买数量超过库存剩余数量,库存剩余" + num + "张");
				}
				// 查询订单 限制
				if (activityPrice.getPayNum() != 0) {// 订单有限制
					if (priceNumber >= activityPrice.getPayNum()) {
						return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("达到最大订单数量");
					}
				}
				// 金额验证
				Double payprice = activityPrice.getPrice().multiply(new BigDecimal(activityEnlist.getBuyNum()))
						.doubleValue();
				if (activityEnlist.getPayMoney().equals(payprice) == false) {
					return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("金额验算不符");
				}
				// 填写报名订单信息
				try {
					// 修改 销售 数量
					int count = activityPriceRepository.updateAddSellNum(activityEnlist.getActivityPriceId(),
							activityEnlist.getBuyNum());
					if (count == 0) {
						throw new Exception("数据修改失败");
					}
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println(e.getMessage());
				}
				activityEnlist.setState(0);
				activityEnlist.setBuildTime(new Date());
				OperatorActivityEnlist operatoractivityEnlist = operatorActivityEnlistRepository.save(activityEnlist);
				return ajaxJson.setSuccess(true).setStatus(200).setData(operatoractivityEnlist).setMsg("下单成功");

			}
			// 不收费
			if (eventDetails.getIsMoney() != null && eventDetails.getIsMoney() == 0) {
				// 判断是否 有订单 每人只许报名一次
				if (enlistNumber >= 1) {
					return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("不可重复报名");
				}
				// 限制 报名人数
				else if (eventDetails.getEnrollment() != 0) {
					Integer joinNum = eventDetails.getEventJoinPersonNum();
					if (joinNum >= eventDetails.getEnrollment()) {
						return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("报名已满");
					}
				}
				// 填写报名订单信息
				activityEnlist
						.setStreamNum(String.valueOf(new Date().getTime() + (int) ((Math.random() * 9 + 1) * 100000)));// 随机生成
																														// 流水订单号
				activityEnlist.setState(1);// 报名成功 1
				activityEnlist.setBuildTime(new Date());
				OperatorActivityEnlist operatoractivityEnlist = operatorActivityEnlistRepository.save(activityEnlist);
				operatorEventDetailsRepository.updateEnrollmentAdd(activityEnlist.getActivityId());// 参加活动票数加一
				// 发送短信息
				try {
					sendCode.sendMessage(activityEnlist.getTelePhone(),
							"尊敬的客户您好，您已成功报名" + eventDetails.getEventTitle() + "活动，感谢您的参与，谢谢！客服热线：4008518585");
				} catch (Exception e) {
					e.printStackTrace();
				}
				return ajaxJson.setSuccess(true).setStatus(200).setData(operatoractivityEnlist).setMsg("下单成功 ");
			}
		}
		return null;
		}
	}

	@Override
	public Object getActivityEnlist(String Id) {
		if (Id != null) {
			String sql = "SELECT b.event_title,b.is_money, b.event_pic_url,b.organizer,b.event_start_time,c.name as  place_name ,"
					+ "d.name as  city_name,b.event_detailed_address,b.event_end_time,a.user_id,a.activity_id,a.link_man,"
					+ "a.tele_phone,a.buy_num,a.pay_money,a.company_name,a.state,a.stream_num,a.build_time,a.id FROM"
					+ " t_operator_activity_enlist a ,t_operator_event_details b LEFT JOIN t_provide_province  c on b.event_place=c.id LEFT JOIN t_provide_city d on b.event_county =d.id WHERE a.id=:id and a.activity_id=b.id";
			Query query = manager.createNativeQuery(sql, operatorEnlistDetails.class);
			query.setParameter("id", Id);
			List<operatorEnlistDetails> enlist = (List<operatorEnlistDetails>) query.getResultList();
			return enlist.get(0);
		}
		return null;
	}

	@Override
	public void deleteActivityEnlistById(String id) {
		operatorActivityEnlistRepository.delete(id);
	}

	@Transactional
	@Override
	public int updateActivityEnlistState(OperatorActivityEnlist operatorActivityEnlist) throws Exception {
		Date date = new Date();
		OperatorActivityEnlist enlist = operatorActivityEnlistRepository.getOne(operatorActivityEnlist.getId());
		String activityId = enlist.getActivityId();
		OperatorEventDetails operatorEventDetails = operatorEventDetailsRepository.findOne(activityId);
		Long signupEndtime = operatorEventDetails.getSignupEndTime().getTime();
		int count = 0;
		if (date.getTime() < signupEndtime) {
			Integer state = operatorActivityEnlist.getState();
			String id = operatorActivityEnlist.getId();
			int orgState = -1;
			if (state == 2) {// 取消
				orgState = 0;
			}
			count = operatorActivityEnlistRepository.updateActivityEnlistState(state, orgState, id);
			if (count == 0) {
				throw new Exception("数据修改失败");
			}
			if (operatorEventDetails.getIsMoney() == 1) {// 收费
				int countnum = activityPriceRepository.updateRemoveSellNum(enlist.getActivityPriceId(),
						enlist.getBuyNum());
				if (countnum == 0) {
					throw new Exception("数据修改失败");
				}
			}
			if (operatorEventDetails.getIsMoney() == 0) {// 不收费
				operatorEventDetailsRepository.updateEnrollmentRemove(enlist.getActivityId(), enlist.getBuyNum());
			}

		}
		return count;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<operatorEnlistDetails> getFenYeEnlistAll(String userId, Integer page, Integer size) {
		String sql = "SELECT b.event_title,b.is_money, b.event_pic_url,b.organizer,b.event_start_time,c.name as  place_name ,"
				+ "d.name as  city_name,b.event_detailed_address,b.event_end_time,a.user_id,a.activity_id,a.link_man,"
				+ "a.tele_phone,a.buy_num,a.pay_money,a.company_name,a.state,a.stream_num,a.build_time,a.id  FROM"
				+ " t_operator_activity_enlist a ,t_operator_event_details b LEFT JOIN t_provide_province  c on b.event_place=c.id LEFT JOIN t_provide_city d on b.event_county =d.id WHERE a.user_id=:userId and a.activity_id=b.id ORDER BY a.build_time DESC";
		Query query = manager.createNativeQuery(sql, operatorEnlistDetails.class);
		int index = (page - 1) * size;
		List<operatorEnlistDetails> enlist = (List<operatorEnlistDetails>) query.setParameter("userId", userId)
				.setMaxResults(size).setFirstResult(index).getResultList();
		return enlist;

	}

	@SuppressWarnings("unchecked")
	@Override
	public OperatorActivityEnlist getFenYeEnlistAndCount(String userId, Integer page, Integer size) {
		Integer count = operatorActivityEnlistRepository.queryCountByUserId(userId);
		OperatorActivityEnlist operatorActivityEnlist = new OperatorActivityEnlist();
		operatorActivityEnlist.setCount(count);
		String sql = "SELECT b.event_title,b.is_money, b.event_pic_url,b.organizer,b.event_start_time,c.name as  place_name ,"
				+ "d.name as  city_name,b.event_detailed_address,b.event_end_time,a.user_id,a.activity_id,a.link_man,"
				+ "a.tele_phone,a.buy_num,a.pay_money,a.company_name,a.state,a.stream_num,a.build_time,a.id FROM"
				+ " t_operator_activity_enlist a ,t_operator_event_details b LEFT JOIN t_provide_province  c on b.event_place=c.id LEFT JOIN t_provide_city d on b.event_county =d.id WHERE a.user_id=:userId and a.activity_id=b.id ORDER BY a.build_time DESC";
		Query query = manager.createNativeQuery(sql, operatorEnlistDetails.class);
		int index = (page - 1) * size;
		List<operatorEnlistDetails> enlist = (List<operatorEnlistDetails>) query.setParameter("userId", userId)
				.setMaxResults(size).setFirstResult(index).getResultList();
		operatorActivityEnlist.setEnlistlist(enlist);
		return operatorActivityEnlist;
	}

	@Transactional
	@SuppressWarnings("unused")
	@Override
	public AjaxJson validateActivityEnlistCoupons(OperatorActivityEnlist operatorActivityEnlist) throws Exception {
		AjaxJson ajaxJson = new AjaxJson();
		String couponId = operatorActivityEnlist.getCouponId();// 商品优惠券id
		String id = operatorActivityEnlist.getId();// 订单id
		OperatorActivityEnlist enlist = operatorActivityEnlistRepository.findOne(id);
		/**
		 * 验证订单 是否存在
		 */
		if (enlist.getId() == null || enlist.equals(null)== true) {
			return ajaxJson.setSuccess(true).setStatus(200).setData(null).setMsg("订单不存在");
		}
		/**
		 * 没有 使用优惠券
		 */
		if (couponId == null || couponId.equals("") == true) {
			Double couponPrice = null;
			operatorActivityEnlistRepository.updateCouponIdAndPrice(id, couponId, couponPrice);
			return ajaxJson.setSuccess(true).setStatus(200).setData("success");
		}
		/**
		 * 使用 优惠券
		 */
		else if (couponId != null || couponId.equals("") != true) {
			String userId = enlist.getUserId();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(sdf.format(new Date()));
			/**
			 * 优惠券 用 逗号 分割
			 */
			String ids[] = couponId.split(",");
			int percentage =Integer.parseInt(keyValueRepository.selectValuessByKeyss("direct_reduction_ratio"));
			double totleAmount = 0;// 优惠券金额
			String mark="0";
			
			for (int numcou = 0; numcou < ids.length; numcou++) {
				/**
				 * 查询 优惠券
				 */
				String jpql = "select new guoanmaker.operator.business.modelnobind.OpersonalUUC(b.id,b.isUsed,b.ocId,"
						+ "b.userId,a.couponstype,a.fullamount,a.subamount,a.lapseamount,b.expiredDate,b.start_date,a.serverid) "
						+ " from PersonalUserCoupon b,OperatorCoupons a  where b.id=:couponId and b.userId=:userId and a.id=b.ocId";
				Query query = manager.createQuery(jpql);
				query.setParameter("couponId", ids[numcou]);
				query.setParameter("userId", userId);
				if(query.getResultList().size()>0) {
					OpersonalUUC enlistCoupons = (OpersonalUUC) query.getSingleResult();
					manager.clear();
					/**
					 * 判断 优惠券 是否 可用
					 */
					if (enlistCoupons.getIsUsed().equals("1") == false && !enlistCoupons.getExpiredDate().before(date)
							&& !enlistCoupons.getStart_date().after(date)
							&& enlistCoupons.getServerid().equals("0") == true) {
						if(enlistCoupons.getCouponstype().equals("1")==true ) {// 满减
							if(enlistCoupons.getFullamount() <= enlist.getPayMoney()) {// 支付金额大于等于优惠券
							 operatorActivityEnlistRepository.updateCouponIdAndPrice(id, couponId,enlistCoupons.getSubamount());
							 return ajaxJson.setSuccess(true).setStatus(200).setData("success").setMsg("验证成功");
							}else {
						     return ajaxJson.setSuccess(true).setStatus(200).setData("failure").setMsg("优惠券不符合使用条件");
							}
						}
						else if(enlistCoupons.getCouponstype().equals("0")) {//直减
							totleAmount+=enlistCoupons.getLapseamount();
						}
					} else {
						mark="1";
						break;
					}
				}
				else {
					return ajaxJson.setSuccess(true).setStatus(200).setData("failure").setMsg("未查到该优惠券信息");	
				}
			}
			/**
			 * 判断 直减合法性
			 */
			if(mark.equals("1")||totleAmount>enlist.getPayMoney()*percentage/100) {
				 return ajaxJson.setSuccess(true).setStatus(200).setData("failure").setMsg("优惠券不符合使用条件");
			}else {
				operatorActivityEnlistRepository.updateCouponIdAndPrice(id, couponId,totleAmount);
				return ajaxJson.setSuccess(true).setStatus(200).setData("success").setMsg("验证成功");
			}
		}
		return ajaxJson.setSuccess(false).setStatus(200).setData("failure");
	}

	@Transactional
	@Override
	public int saveStreamNum(OperatorActivityEnlist operatorActivityEnlist) {
		Integer count = operatorActivityEnlistRepository.updateStreamNum(operatorActivityEnlist.getId(),
				operatorActivityEnlist.getStreamNum());
		return count;
	}

	/**
	 * 发起支付接口
	 */
	@Override
	public PayInfo paymentActivityEnlist(String id, String channel, String back_url) {
		PayInfo payinfor = new PayInfo();
		OperatorActivityEnlist activityEnlist = operatorActivityEnlistRepository.findOne(id);
		String uid = activityEnlist.getUserId();// 用户id
		String systemCode = "10";// 平台账号
		String platOrderId = id;// 业务平台订单号
		String backUrl = null;
		try {
			backUrl = URLEncoder.encode(back_url, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		// 支付金额
		int amount = Integer.parseInt((activityEnlist.getPayMoney() * 100 + "").substring(0,
				(activityEnlist.getPayMoney() * 100 + "").indexOf(".")));
		Integer card_type = null;
		Integer card_amount = null;
		if (activityEnlist.getCouponId() != null && activityEnlist.getCouponId().equals("")==false  ) {// 使用优惠券
			card_type = 1;// 使用优惠券类型 1平台优惠券
			// 优惠券金额：分
			card_amount = Integer.parseInt((activityEnlist.getCouponPrice() * 100 + "").substring(0,
					(activityEnlist.getCouponPrice() * 100 + "").indexOf(".")));
		}
		if (activityEnlist.getCouponId() == null || activityEnlist.getCouponId().equals("")==true) {
			card_type = 0;// 使用优惠券类型 0不使用
			card_amount = 0; // 优惠券金额：分
		}
		Integer express_fee = 0;// 快递费金额：分
		String originalId = "00000000000000000000000000000001";// 平台服务商编号
		String companyName = "国安创客";// 服务商名称
		String companyTitle = "国安创客";// 服务商公司名称
		Integer isJava = 1;// 是否来自java新平台，1是 0否
		try {
			URL url = new URL("https://tpay.gack.citic/pay?uid=" + URLEncoder.encode(uid,"utf-8") + "&systemCode=" + URLEncoder.encode(systemCode,"utf-8")
					+ "&platOrderId=" +  URLEncoder.encode(platOrderId,"utf-8") + "&channel=" + URLEncoder.encode(channel,"utf-8") + "&amount=" + amount + "&card_type="
					+  card_type + "&card_amount=" + card_amount + "&express_fee=" + express_fee + "&originalId="
					+ URLEncoder.encode(originalId,"utf-8") + "&companyName=" + URLEncoder.encode(companyName,"utf-8") + "&companyTitle=" + URLEncoder.encode(companyTitle,"utf-8") + "&back_url="
					+ backUrl + "&isJava=" + isJava + "");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setAllowUserInteraction(false);
			conn.setUseCaches(false);
			InputStream input = conn.getInputStream();
			int resLen = 0;
			byte[] res = new byte[1024];
			StringBuilder sb = new StringBuilder();
			while ((resLen = input.read(res)) != -1) {
				sb.append(new String(res, 0, resLen));
			}
			String jsonStr = sb.toString();
			PayAnaiyInfor pay = new PayAnaiyInfor();
			payinfor = pay.getPayInfo(jsonStr, channel);
			operatorActivityEnlistRepository.updateStreamNum(id, payinfor.getId());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return payinfor;
	}

	@Override
	@Transactional
	public int updateEnlistPayState(String id, String streamNum) {
		OperatorActivityEnlist enlist = operatorActivityEnlistRepository.findOne(id);
		if (enlist.getState() == 1) {// 如果该订单已支付跳出
			return 101;
		}
		Integer count = null;
		try {
			URL url = new URL("https://tpay.gack.citic/select/payorder?pingId=" + streamNum + "");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setAllowUserInteraction(false);
			conn.setUseCaches(false);
			InputStream input = conn.getInputStream();
			int resLen = 0;
			byte[] res = new byte[1024];
			StringBuilder sb = new StringBuilder();
			while ((resLen = input.read(res)) != -1) {
				sb.append(new String(res, 0, resLen));
			}
			String jsonStr = sb.toString();
			if (jsonStr.equals("1") == true) {
				Integer orgState = 0;
				Integer state = 1;
				count = operatorActivityEnlistRepository.updateActivityEnlistState(state, orgState, id);// 订单

				// 支付
				OperatorEventDetails operatorEventDetails = operatorEventDetailsRepository
						.findOne(enlist.getActivityId());
				// 发送短信息
				try {
					sendCode.sendMessage(enlist.getTelePhone(),
							"尊敬的客户您好，您已成功报名" + operatorEventDetails.getEventTitle() + "活动，感谢您的参与，谢谢！客服热线：4008518585");
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (enlist.getCouponId() != null && enlist.getCouponId().equals("")==false ) {
					String ids[] = enlist.getCouponId().split(",");
					for (int numcou = 0; numcou < ids.length; numcou++) {
						PersonalUserCoupon personalUserCoupon = personalUserCouponRepository.findOne(ids[numcou]);
						personalUserCouponRepository.updateIsUsedByid(ids[numcou]);
						operatorCouponsRepository.updateBeenusedByid(personalUserCoupon.getOcId());
					}
				}
			} else {
				return 101;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public OperatorEventDetails queryActivityUrl(String userId, String activityId) {
		OperatorEventDetails eventDetails = operatorEventDetailsRepository.findOne(activityId);
		int count = operatorActivityEnlistRepository.queryCountByUserIdAndActivity(userId, activityId);
		OperatorEventDetails operatorEventDetails = new OperatorEventDetails();
		if (eventDetails.getIsMoney() != null && eventDetails.getIsMoney() == 1) {// 收费
			if (count >= eventDetails.getUnitNum()) {
				operatorEventDetails.setId("-104");
				return operatorEventDetails;
			}
		}
		if (eventDetails.getIsMoney() != null && eventDetails.getIsMoney() == 0) {// 不收费
			if (count >= 1) {
				operatorEventDetails.setId("-104");
				return operatorEventDetails;
			}
		}
		operatorEventDetails.setId(activityId);
		operatorEventDetails.setEventUrl(eventDetails.getEventUrl());
		operatorEventDetails.setRegistrationFormDetails(eventDetails.getRegistrationFormDetails());
		return operatorEventDetails;
	}

}
